import type {
  EnergyDataReportList,
  InitInputIndex,
  ReportColumnsItem,
} from '../types'
import { uuid } from '@/utils'

function useContextmenu(option: {
  visible: Ref<boolean>
  left: Ref<number>
  top: Ref<number>
  statementRef: Ref<HTMLElement | null>
  lists: Ref<
    EnergyDataReportList<{
      key: string
      value: string | number
      editable?: boolean
      [propName: string]: any
    }>[]
  >
  flattenColumns?: ComputedRef<Omit<ReportColumnsItem, 'children'>[]>
  initInputIndex: InitInputIndex
  rowIndex: Ref<number>
  createAEmptyRow?: () => any
}) {
  const {
    visible,
    left,
    top,
    statementRef,
    lists,
    flattenColumns,
    initInputIndex,
    rowIndex: _rowIndex,
    createAEmptyRow: _createAEmptyRow,
  } = toValue(option)

  // 选中某一行的情况下右键操作
  function onContextmenu(evt: MouseEvent) {
    evt.preventDefault()

    const statementTableRef = toValue(statementRef)

    let tr: any = evt.target
    while (tr) {
      if ((tr.tagName || '').toUpperCase() === 'TR') {
        break
      }
      tr = tr.parentNode
    }
    if (tr && statementTableRef) {
      const menuMinWidth = 105
      const offsetLeft = statementTableRef.getBoundingClientRect().left // container margin left
      const offsetWidth = statementTableRef.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const l = evt.clientX - offsetLeft + 15 // 15: margin right

      if (l > maxLeft) {
        left.value = maxLeft
      }
      else {
        left.value = l
      }

      top.value = evt.clientY - 100
      visible.value = true
    }
  }

  // 删除 rowIndex 行
  function delRow() {
    const rowIndex = toValue(_rowIndex)
    ElMessageBox.confirm('确定要删除这一行？', '温馨提示')
      .then(() => {
        lists.value.splice(Number(rowIndex), 1)
        visible.value = false
      })
      .catch(() => {})
  }

  const createAEmptyRow = () => {
    if (_createAEmptyRow) {
      return _createAEmptyRow()
    }
    return (toValue(flattenColumns) || []).map(v => ({
      key: v.prop,
      value: '',
      editable: true,
    }))
  }

  // 在 rowIndex 行前添加一行
  function prependRow() {
    const rowIndex = Number(toValue(_rowIndex))
    const emptyRow = createAEmptyRow()
    if (rowIndex > -1) {
      lists.value.splice(rowIndex, 0, {
        uuid: uuid(),
        data: [...emptyRow],
      })

      nextTick(() => {
        initInputIndex()
      })
    }
    visible.value = false
  }

  // 在 rowIndex 行后添加一行
  function appendRow() {
    const rowIndex = Number(toValue(_rowIndex))
    const emptyRow = createAEmptyRow()
    if (rowIndex > -1) {
      lists.value.splice(rowIndex + 1, 0, {
        uuid: uuid(),
        data: [...emptyRow],
      })

      nextTick(() => {
        initInputIndex()
      })
    }
    visible.value = false
  }

  return {
    visible,
    left,
    top,

    onContextmenu,
    delRow,
    appendRow,
    prependRow,
  }
}

export default useContextmenu
